package com.ba.base.view.video

import android.graphics.Bitmap
import android.media.MediaMetadataRetriever
import android.media.MediaPlayer
import android.os.Build
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.MediaController
import com.ba.base.R
import com.ba.base.utils.LogUtils
import com.danikula.videocache.HttpProxyCacheServer
import com.ba.base.view.AbsActivity
import com.ba.base.view.dialog.ProgressDialog
import kotlinx.android.synthetic.main.activity_video_player.*

/**
 * 视频播放
 */
class VideoPlayerActivity(
    override val layoutId: Int = R.layout.activity_video_player,
    override val reload: Boolean = false
) : AbsActivity() {
    private var dialog: ProgressDialog? = null
    private var proxy: HttpProxyCacheServer? = null
    override fun initData(savedInstanceState: Bundle?) {
        super.initData(savedInstanceState)


    }

    override fun initView() {
        super.initView()
        setTranslucentStatus()
        //视频url
        val uri = intent.getStringExtra("videoUrl")
        LogUtils.d("videoUrl", uri)
        //视频缓存代理
        val proxy: HttpProxyCacheServer = getProxy()
        val proxyUrl: String = proxy.getProxyUrl(uri)
        videoView.setVideoPath(proxyUrl)
        //加载视频第一帧
        val bitmap = getNetVideoBitmap(uri)
        imageView.setImageBitmap(bitmap)//对应的ImageView赋值图片

//        videoView.setVideoURI(Uri.parse(uri))
        val mediaController = MediaController(this)
        mediaController.setMediaPlayer(videoView)
        videoView.setMediaController(mediaController)
        videoView.start()
        dialog = ProgressDialog(this).apply {
            setText("加载中...")
        }
        dialog?.show()
        videoView.setOnPreparedListener {
            it.isLooping = true
            it.setOnInfoListener(MediaPlayer.OnInfoListener { _, what, _ -> //开始播放时，就把显示第一帧的ImageView gone 掉
                if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START) {
                    dialog?.dismiss()
                    // video started; hide the placeholder.
                    imageView.visibility = View.GONE
                    //videoView.seekTo(0);
                    return@OnInfoListener true
                }
                false
            })
        }
    }

    override fun onPause() {
        super.onPause()
        videoView.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    /**
     * 设置沉浸式状态栏
     */
    private fun setTranslucentStatus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { //安卓版本大于4.4
            val window = window
            val layoutParams = window.attributes
            layoutParams.flags =
                layoutParams.flags or WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
            window.attributes = layoutParams
        }
    }

    /**
     * 获取网络视频第一帧
     */
    private fun getNetVideoBitmap(videoUrl: String?): Bitmap? {
        var bitmap: Bitmap? = null
        val retriever = MediaMetadataRetriever()
        try {
            //根据url获取缩略图
            retriever.setDataSource(videoUrl, HashMap())
            //获得第一帧图片
            bitmap = retriever.frameAtTime
        } catch (e: IllegalArgumentException) {
            e.printStackTrace()
        } finally {
            retriever.release()
        }
        return bitmap
    }
    private fun getProxy(): HttpProxyCacheServer {
        return proxy ?: newProxy()!!
    }
    private fun newProxy(): HttpProxyCacheServer? {
        return HttpProxyCacheServer.Builder(this)
            .maxCacheSize(1024 * 1024 * 1024.toLong()) // 1 Gb for cache
            .build()
    }
}
